#include <stdio.h>
#include "zlog.h"
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#define RUN_TIME 	 49 
#define PTHREAD_NUM  20
#define USE_RUN_TIME 1

static pthread_mutex_t mutex;

void *pthread_start(void *arg)
{
	int ret = 0;
	zlog_category_t *zc = NULL;
	int pth_num;
	char buf[32];

	//pthread_mutex_lock(&mutex);
	pth_num = *(int *)arg;
	pthread_mutex_unlock(&mutex);
	snprintf(buf, 32, "Pthread%02d", pth_num);

	zc = zlog_get_category("Pthread");
	if(zc == NULL)
	{
		printf("zlog_get_category failed.\n");
		return (void*)-1;
	}
	zlog_info(zc, "[%s]arg = %d",buf, pth_num);
#ifdef USE_RUN_TIME 	
	while(1)
	{
		ret++;
		zlog_info(zc, "[%s]ret = %d",buf, ret);
		sleep(1);
		if(ret > RUN_TIME) break;
	}
#endif	
	return (void*)0;
}

int main(int argc, char *argv[])
{
	int ret = 0;
	pthread_t pid[PTHREAD_NUM];
	int i = 0;
	int rc = 0;
	zlog_category_t *zc = NULL;
	int ptharg = 0;

	pthread_mutex_init(&mutex, NULL);
	//rc = zlog_init("pthread_test.conf");
	rc = zlog_init("zlog.conf");
	if(rc)
	{
		printf("zlog_init failed in main.\n");
		return -1;
	}
	zc = zlog_get_category("Pthread");
	if(zc == NULL)
	{
		printf("zlog_get_category failed.\n");
		return -1;
	}
	for(; i < PTHREAD_NUM; i++)
	{
		pthread_mutex_lock(&mutex);
		ptharg = i;
		ret = pthread_create(&pid[i],NULL, pthread_start, (void*)&ptharg);
	//	pthread_mutex_unlock(&mutex);
		if(ret)
		{
			zlog_error(zc, "pthread_create %d:%s,ret=%d",\
					i+1, strerror(errno), ret);
			pthread_mutex_unlock(&mutex);
		}
		else
			zlog_debug(zc, "create pthread %d success,pid = %ld",\
					i+1, pid[i]);
	}
#ifdef USE_RUN_TIME
	i = RUN_TIME;
	while(i--)
	{
		zlog_info(zc, "left %ds...", i);
		sleep(1);
	}
#endif
	for(i = 0; i < PTHREAD_NUM; i++)
	{
		ret = pthread_join(pid[i], NULL);
		if(ret)
		{
			zlog_error(zc, "pthread_join:%s,ret=%d",strerror(errno),ret);
		}
		else
		{
			zlog_debug(zc, "join pthread[%ld] success.", pid[i]);
		}
	}
	pthread_mutex_destroy(&mutex);
	zlog_fini();

	return 0;
}

